import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common";
import { ApiException } from "../exceptions/api.exceptions";
import AjaxResult from "../class/ajax.result.class";

@Catch()

export default class AllExceptionsFilter implements ExceptionFilter {
    catch(exception: any, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse();
        // const { status, result } = this.err
    }

    errorResult(exception: any) {
        const status = exception instanceof HttpException
                ? exception.getStatus()
                : HttpStatus.INTERNAL_SERVER_ERROR;

        const code = exception instanceof ApiException
                ? (exception as ApiException).getErrCode()
                : status;

        let message: string;
        if (exception instanceof HttpException) {
            const response = exception.getResponse();
            message = (response as any).message ?? response;
        } else {
            message = `${exception}`;
        }

        return {
            status,
            result: AjaxResult.error(code, message)
        }   
    }
}